define(['app'], function(app) {
    app.controller('uploadImage', function($uibModalInstance, Upload, _dialog) {
        var self = this;

        self.init = function() {
            self.url = '';
            self.name = '';
        }

        self.upload = function(file) {
            if (file != null) {
                if (/\.(jpg|png|gif)$/i.test(file.name)) {
                    self.name = file.name;
                    // upload image
                    Upload.upload({
                        url: '/note/image/upload',
                        method: 'POST',
                        data: {
                            'Content-Type': (file.type != '' ? file.type : 'application/octet-stream'),
                            'filename': file.name,
                            'file': file
                        }
                    }).then(function(response) {
                        var filename = response.data;
                        if (filename) {
                            self.url = '/note/images/' + filename;
                        }
                    });
                } else {
                    _dialog.alert('提示信息', '您上传的不是有效的图片文件！');
                }
            }
        }

        self.insert = function(valid) {
            if (valid) {
                $uibModalInstance.close({ url: self.url, name: self.name });
            }
        }

        self.cancel = function() {
            $uibModalInstance.dismiss();
        }
    });
});
